package com.hyk.commonLib.common.adapter;

import android.os.Bundle;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.ViewPager;

import org.jetbrains.annotations.NotNull;

/**
 * Created by 贺玉琨 on 2019/3/6 0006.
 *
 * <p/>
 * 对于 activity 后台被销毁后重建导致 viewPager 部分 fragment 空白的问题，目前暂无简便解决办法。
 * <p/>
 * 可在 {@link android.app.Activity#onCreate(Bundle savedInstanceState)} 方法中加入判断
 * <p/>
 * <pre>
 *   if (savedInstanceState != null) {
 *       adapter.clear(viewPager);
 *   }
 * </pre>
 */
public class FragmentFactoryPagerAdapter extends androidx.fragment.app.FragmentPagerAdapter {

    private final FragmentFactory fragmentFactory;
    private final FragmentManager fm;

    public FragmentFactoryPagerAdapter(FragmentManager fm, @NotNull FragmentFactory fragmentFactory) {
        super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
        this.fm = fm;
        this.fragmentFactory = fragmentFactory;
    }

    @NotNull
    @Override
    public Fragment getItem(int arg0) {
        return fragmentFactory.create(arg0);
    }

    @Override
    public int getCount() {
        return fragmentFactory.getSize();
    }

    /**
     * 清除缓存fragment
     *
     * @param container ViewPager
     */
    public void clear(ViewPager container) {
        FragmentTransaction mCurTransaction = this.fm.beginTransaction();

        for (int i = 0; i < getCount(); i++) {
            long itemId = this.getItemId(i);
            String name = makeFragmentName(container.getId(), itemId);
            Fragment fragment = this.fm.findFragmentByTag(name);
            if (fragment != null) {//根据对应的ID，找到fragment，删除
                mCurTransaction.remove(fragment);
            }
        }
        mCurTransaction.commitNowAllowingStateLoss();
    }

    public Fragment getFragmentAt(ViewPager container, int position) {
        long itemId = this.getItemId(position);
        String tag = makeFragmentName(container.getId(), itemId);
        return fm.findFragmentByTag(tag);
    }

    /**
     * 不销毁fragment
     */
    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
//        super.destroyItem(container, position, object);
    }

    /**
     * 等同于FragmentPagerAdapter的makeFragmentName方法，
     * 由于父类的该方法是私有的，所以在此重新定义
     *
     * @param viewId
     * @param id
     * @return String
     */
    private static String makeFragmentName(int viewId, long id) {
        return "android:switcher:" + viewId + ":" + id;
    }

    public interface FragmentFactory {
        Fragment create(int index);

        int getSize();
    }
}